package com.yint.browser.widget;

import android.content.Context;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.yint.browser.R;

/**
 * 该View用于盛载 浏览器播放视频等，点击全屏时要展示的customView
 */
public class CustomViewContainer extends FrameLayout {

    private final String TAG = "CustomViewContainer";

    //标题延迟多少秒隐藏
    private final int TITLE_HIDE_DELAY_TIME = 3000;

    private FrameLayout containerFl;
    private LinearLayout titleLl;
    private LinearLayout backLl;
    private TextView titleTv;

    private WebChromeClient.CustomViewCallback callback;

    public CustomViewContainer(@NonNull Context context) {
        this(context, null);
    }

    public CustomViewContainer(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomViewContainer(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
        initAttrs(context, attrs);
        bindView();
    }

    private void initView(Context context) {
        //加载布局文件
        View view = LayoutInflater.from(context).inflate(R.layout.custom_view_container_layout, this);
        containerFl = view.findViewById(R.id.container_fl);

        titleLl = view.findViewById(R.id.title_ll);

        backLl = view.findViewById(R.id.back_ll);
        titleTv = view.findViewById(R.id.title_tv);

        backLl.setOnClickListener(onClickListener);
    }

    private void initAttrs(Context context, AttributeSet attrs) {

    }

    private void bindView() {

    }

    public void setTitle(String title) {
        Log.d(TAG, "setTitle title:" + title);
        titleTv.setText(title);
    }

    public void showCustomView(View customView, WebChromeClient.CustomViewCallback callback) {
        Log.d(TAG, "setCustomView");
        //如果view 已经存在，则隐藏
        if (customView == null) {
            return;
        }
        customView.setVisibility(VISIBLE);
        containerFl.addView(customView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        this.callback = callback;
        //显示title
        changeTitleViewVisible(true);
        hideTitleDelay();
    }

    public void hideCustomView() {
        Log.d(TAG, "hideCustomView");
        if (callback != null) {
            try {
                callback.onCustomViewHidden();
            } catch (Exception e) {
            }
        }
        containerFl.removeAllViews();
        this.callback = null;
    }

    private void hideTitleDelay() {
        Log.d(TAG, "hideTitleDelay delay:" + TITLE_HIDE_DELAY_TIME);
        handler.removeMessages(WHAT_HIDE_TITLE_DELAY);
        handler.sendEmptyMessageDelayed(WHAT_HIDE_TITLE_DELAY, TITLE_HIDE_DELAY_TIME);
    }

    public void clear() {
        try {
            handler.removeCallbacksAndMessages(null);
            containerFl.removeAllViews();
            callback = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        Log.d(TAG, "dispatchTouchEvent action:" + event.getAction());
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (titleLl.getVisibility() == VISIBLE) {
                    if (inRangeOfView(backLl, event)) {
                        Toast.makeText(getContext(),"dispatchTouchEvent inRangeOfView backLl",Toast.LENGTH_SHORT).show();
                        onClickBackIv();
                    }
                    changeTitleViewVisible(false);
                } else {
                    changeTitleViewVisible(true);
                    hideTitleDelay();
                }
                break;
        }
        return super.dispatchTouchEvent(event);
    }

    private boolean inRangeOfView(View view, MotionEvent ev) {
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        Rect viewRect = new Rect();
        viewRect.left = location[0];
        viewRect.top = location[1];
        viewRect.right = view.getWidth() + location[0];
        viewRect.bottom = view.getHeight() + location[1];
        return viewRect.contains((int) ev.getX(), (int) ev.getY());
    }

    private void changeTitleViewVisible(boolean visible) {
        Log.d(TAG, "changeTitleViewVisible visible:" + visible);
        titleLl.setVisibility(visible ? VISIBLE : GONE);
    }

    private final OnClickListener onClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v == backLl) {
                Log.d(TAG, "onClickListener onClick backLl");
                Toast.makeText(getContext(),"onClickListener onClick backLl",Toast.LENGTH_SHORT).show();
                onClickBackIv();
            }
        }
    };

    private void onClickBackIv() {
        Log.d(TAG, "onClickBackIv");
        if (callback != null) {
            try {
                callback.onCustomViewHidden();
            } catch (Exception e) {
            }
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        clear();
    }

    private final int WHAT_HIDE_TITLE_DELAY = 0x1001;

    private final Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case WHAT_HIDE_TITLE_DELAY:
                    changeTitleViewVisible(false);
                    break;
            }
        }
    };
}
